package com.nota.Databackup;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @author 胡超雄
 * @date 2024/03/18 16:27
 * @desc
 */
@Slf4j
@Component
public class DataBackUp {

    @Value("${tables}")
    private String tables;

    @Value("${delcommand}")
    private String delcommand;


    /**
     * 备份数据 ,每天晚上四点二十执行
     */
    @Scheduled(cron = "0 20 04 * * ?")
    public void backUp() {
        LocalDate now = LocalDate.now();
        String today = now.toString();

        String yesterday = now.minusDays(1).toString();

        // 直接指定哪些表需要备份
        String[] allTable = tables.split(",");
        for (String tableName : allTable) {
            try {
                create(tableName, today, yesterday);
            } catch (Exception e) {
                log.error("备份表[{}]失败", tableName, e);
            }

        }


        log.info("执行结果:");

    }

    /**
     * 备份数据
     *
     * @param tableName
     */
    private void create(String tableName, String today, String yesterday) {
        String createCommand = "clickhouse-backup create  -t default." + tableName + "  " + today + "_" + tableName;
        log.info("当前的备份数据命令{}", createCommand);
        String result = command(createCommand);
        log.info("当前的备份数据结果{}", result);
        //成功就执行删除命令
        if (result.contains("info done")) {
            String delCommand = delcommand + yesterday + "_" + tableName;
            log.info("当前删除备份数据命令{}", delCommand);
            command(delCommand);
        }
    }


    private String command(String command) {
        String result = "";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            //等待命令执行完成
            process.waitFor(1000, TimeUnit.SECONDS);
            try (InputStream is = process.getInputStream();
                 Scanner input = new Scanner(is)) {
                StringBuilder sb = new StringBuilder();
                while (input.hasNextLine()) {
                    sb.append(input.nextLine()).append("\n");
                }
                result = sb.toString();
                log.info(result);
            }
        } catch (Exception e) {
            log.error("执行有问题", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return result;

    }


}
